/**
 * Copyright 2021 xieyuanhui
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.milantiejiang.tuto;

import android.util.Log;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Date;

public class ServiceThread extends Thread{
    private final String TAG=getClass().getSimpleName();
    Socket socket;

    public ServiceThread(Socket socket) {
        Log.i(TAG, "线程ID：" + this.getId() + " 状态：" + this.getState());
        this.socket = socket;
    }

    @Override
    public void run() {
        super.run();
        InputStream input = null;//来自客户端的数据
        DataInputStream dinput = null;
        OutputStream output = null;//发送给客户端的数据
        DataOutputStream doutput = null;
        try {
            input = socket.getInputStream();
            if(SocketService.mType==1){
                dinput = new DataInputStream(input);
                byte[] readbuf=new byte[1024];
                dinput.read(readbuf);
                int dataLen= Utils.bytes2Int_LE(Utils.subByte(readbuf,4,7));
                Log.i(TAG,"dataLen:"+dataLen);
                String dataStr= Utils.hexBytes2Str(Utils.subByte(readbuf,8,dataLen));
                Log.i(TAG, "服务端收到消息："+dataStr);
                if(dataStr.equals(CommContent.SEND_FILE)){
                    //客户端发起传输文件流程
                    SocketService.mType=2;
                    //服务端响应客户端请求
                    output = socket.getOutputStream();
                    doutput = new DataOutputStream(output);
                    byte[] rep=CommContent.SEND_FILE.getBytes();
                    byte[] repStr= Utils.buildMsg(Utils.int2Bytes_LE(rep.length),rep);
                    doutput.write(repStr,0,repStr.length);
                    Log.i(TAG, "服务端响应消息："+ Utils.bytesToHexString(repStr));
                    doutput.flush();
                }else if(dataStr.equals(CommContent.DOWLOAD_FILE)){
                    //客户端发起传输文件流程
                    SocketService.mType=3;
                    //服务端响应客户端请求
                    output = socket.getOutputStream();
                    doutput = new DataOutputStream(output);
                    byte[] rep=CommContent.DOWLOAD_FILE.getBytes();
                    byte[] repStr= Utils.buildMsg(Utils.int2Bytes_LE(rep.length),rep);
                    doutput.write(repStr,0,repStr.length);
                    Log.i(TAG, "服务端响应消息："+ Utils.bytesToHexString(repStr));
                    doutput.flush();
                    //服务端向客户端传输文件
                    output = socket.getOutputStream();
                    doutput = new DataOutputStream(output);
                    File file = new File(MainActivity.path+"serviceFile.txt");
                    DataInputStream fileInputStream = new DataInputStream(new FileInputStream(file));
                    byte[] buf = new byte[1024];
                    int len = 0;
                    Log.i(TAG, Thread.currentThread().getName() + " 向客户端发送文件");
                    while ((len = fileInputStream.read(buf)) != -1) {
                        doutput.write(buf, 0, len);
                    }
                    Log.i(TAG, "文件传输完成！！");
                    doutput.flush();
                    fileInputStream.close();
                    SocketService.mType=1;
                }else {
                    SocketService.mType=1;
                    output = socket.getOutputStream();
                    doutput = new DataOutputStream(output);
                    byte[] rep="server response".getBytes();
                    byte[] repStr= Utils.buildMsg(Utils.int2Bytes_LE(rep.length),rep);
                    doutput.write(repStr,0,repStr.length);
                    Log.i(TAG, "服务端响应消息："+ Utils.bytesToHexString(repStr));
                    doutput.flush();
                }
            }else if(SocketService.mType==2){
                //处理文件接收任务
                Log.i(TAG, "接收客户端的文件");
                dinput=new DataInputStream(input);

                Date date=new Date();
                DataOutputStream fileDataOutputStream=new DataOutputStream(new FileOutputStream(MainActivity.path+"serviceFile"+date.getTime()+".txt"));
                byte[] buf=new byte[1024];
                int len=0;
                while ((len=dinput.read(buf))!=-1){
                    fileDataOutputStream.write(buf,0,len);
                    Log.i(TAG, "写入文件... "+len);
                }
                Log.i(TAG, "文件下载完成！！");
                fileDataOutputStream.flush();
                fileDataOutputStream.close();
                SocketService.mType=1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(input!=null){
                    input.close();
                }
                if(dinput!=null){
                    dinput.close();
                }
                if(output!=null){
                    output.close();
                }
                if(doutput!=null){
                    doutput.close();
                }
                Log.i(TAG, "Stream close");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
